#
# Imports
#
import os
import sys
import urllib
import xbmc
import xbmcgui
from urlparse import urlparse
import zipfile
import shutil
import xbmczone_constants

#
# Main class
#
class Main:
	def __init__(self) :
		# Init
		debug = False
		
		#
		# Parse parameters...
		#
		params = dict(part.split('=') for part in sys.argv[ 2 ][ 1: ].split('&'))
		
		#
		# Init
		#
		addon_name         =                             urllib.unquote ( params[ "name" ] )
		addon_type         =                                              params[ "type" ]
		addon_zip_url      = "http://xbmczone.com/download.asp?id=%s" % ( params[ "id" ] )
		addon_zip_local    = os.path.join( xbmczone_constants.XBMC_TEMP_PATH, "xbmczone-addon.zip" )
		addon_install_path =                                              params[ "install-path" ]

		# Debug info
		if debug :
			print "=== xbmczone_download_install.pf ==="
			print "NAME         = " + addon_name
			print "TYPE         = " + addon_type
			print "DOWNLOAD URL = " + addon_zip_url
			print "ZIP LOCAL    = " + addon_zip_local
			print "INSTALL PATH = " + addon_install_path

		# Download addon...
		self.download_addon ( addon_name, addon_type, addon_zip_url, addon_zip_local )

		# Install addon...
		self.install_addon ( addon_name, addon_type, addon_zip_local, addon_install_path )

	#
	# Download addon...
	#
	def download_addon (self, addon_name, addon_type, addon_zip_url, addon_zip_local) :
		dp = xbmcgui.DialogProgress()
		if (addon_type == "Plugin") :
			dp.create(xbmc.getLocalizedString(30000), xbmc.getLocalizedString(30401) % addon_name)
		elif (addon_type == "Script") :
			dp.create(xbmc.getLocalizedString(30000), xbmc.getLocalizedString(30402) % addon_name)
		urllib.urlretrieve( addon_zip_url, addon_zip_local, lambda nb, bs, fs, url=addon_zip_url : self.download_progress_hook( nb, bs, fs, addon_zip_local, dp ) )
		dp.close()

	#
	# Download progressbar handler...
	#
	def download_progress_hook (self, numblocks, blocksize, filesize, url=None, dp=None, ratio=1.0 ):
		try:
			percent = min( ( numblocks * blocksize * 100) / filesize, 100 )
			dp.update( int( percent * ratio ) )
		except:
			percent = 100
			dp.update( int( percent * ratio ) )
		if dp.iscanceled():
			raise IOError

	#
	# Install addon...
	#
	def install_addon( self, addon_name, addon_type, addon_zip_local, addon_install_path ):
		# Init
		answer_do_install = True
		
		#
		# Extract addon zip...
		#
		zip = zipfile.ZipFile (addon_zip_local, "r")
		for zip_entry in zip.namelist():
			#
			# Directory...
			#
			if zip_entry.endswith( '/' ):
				dir_path = os.path.join ( addon_install_path, zip_entry )
				
				# Directory exists, ask to overwrite...
				if os.path.isdir(dir_path):
					dialog = xbmcgui.Dialog()
					answer_do_install = xbmcgui.Dialog().yesno( xbmc.getLocalizedString(30000), "'%s' is already installed, overwrite?" % (addon_name) )
					if answer_do_install :
						shutil.rmtree  (dir_path)
						os.mkdir (dir_path)
					else :
						break
				# Create directory...
				else :
					os.mkdir (dir_path)
			#
			# File...
			#
			else:
				file_path = os.path.join(addon_install_path, zip_entry)
				outfile = open(file_path, 'wb')
				outfile.write( zip.read(zip_entry) )
				outfile.close()
		zip.close()
		
		#
		# Cleanup
		#
		os.remove( addon_zip_local )
		
		#
		# Done (install? = yes)
		#
		if answer_do_install :
			if (addon_type == "Plugin") :
				xbmcgui.Dialog().ok( xbmc.getLocalizedString(30000), xbmc.getLocalizedString(30403) + "\n" + addon_install_path)
			elif (addon_type == "Script") :
				xbmcgui.Dialog().ok( xbmc.getLocalizedString(30000), xbmc.getLocalizedString(30404) + "\n" + addon_install_path)

#
# EOF
#